/**
 * @file content.js
 * @description 内容脚本，负责页面内容的提取和转换
 */

import TurndownService from 'turndown';
import { Readability } from '@mozilla/readability';
import DOMPurify from 'dompurify';

class ContentProcessor {
    constructor() {
        this.turndownService = new TurndownService({
            headingStyle: 'atx',
            codeBlockStyle: 'fenced',
            emDelimiter: '*'
        });

        // 配置自定义规则
        this.configureCustomRules();
    }

    /**
     * 配置Turndown的自定义转换规则
     */
    configureCustomRules() {
        // 表格转换规则
        this.turndownService.addRule('tables', {
            filter: ['table'],
            replacement: function(content, node) {
                const rows = node.rows;
                if (!rows || rows.length === 0) return '';
                
                const headers = Array.from(rows[0].cells).map(cell => cell.textContent.trim());
                const alignments = Array.from(rows[0].cells).map(() => ':--');
                const body = Array.from(rows).slice(1).map(row => {
                    return '| ' + Array.from(row.cells).map(cell => cell.textContent.trim()).join(' | ') + ' |';
                }).join('\n');

                return '\n| ' + headers.join(' | ') + ' |\n' +
                       '| ' + alignments.join(' | ') + ' |\n' +
                       body + '\n\n';
            }
        });

        // 代码块转换规则
        this.turndownService.addRule('fencedCodeBlock', {
            filter: function(node) {
                return (
                    node.nodeName === 'PRE' &&
                    node.firstChild &&
                    node.firstChild.nodeName === 'CODE'
                );
            },
            replacement: function(content, node) {
                const language = node.firstChild.className.replace('language-', '') || '';
                return '\n```' + language + '\n' + node.firstChild.textContent + '\n```\n\n';
            }
        });

        // 图片转换规则
        this.turndownService.addRule('images', {
            filter: 'img',
            replacement: (content, node) => {
                const alt = node.alt || '';
                const src = node.src || '';
                const title = node.title ? ` "${node.title}"` : '';
                return src ? `![${alt}](${src}${title})` : '';
            }
        });
    }

    /**
     * 提取页面主要内容
     * @returns {Object} 包含标题和主要内容的对象
     */
    extractContent() {
        // 克隆文档并清理
        const documentClone = document.cloneNode(true);
        const cleanDoc = DOMPurify.sanitize(documentClone.documentElement.outerHTML, {
            FORBID_TAGS: ['script', 'style', 'iframe', 'frame', 'object', 'embed'],
            FORBID_ATTR: ['onclick', 'onload', 'onerror']
        });
        
        // 创建新的文档解析器
        const parser = new DOMParser();
        const doc = parser.parseFromString(cleanDoc, 'text/html');
        
        // 使用 Readability 提取主要内容
        const reader = new Readability(doc);
        const article = reader.parse();

        return {
            title: article.title,
            content: article.content,
            excerpt: article.excerpt,
            byline: article.byline
        };
    }

    /**
     * 转换HTML为Markdown
     * @param {string} html HTML内容
     * @returns {string} Markdown文本
     */
    convertToMarkdown(html) {
        // 清理HTML
        const cleanHtml = DOMPurify.sanitize(html);
        return this.turndownService.turndown(cleanHtml);
    }

    /**
     * 生成元数据
     * @returns {string} Markdown格式的元数据
     */
    generateMetadata() {
        const metadata = {
            title: document.title,
            url: window.location.href,
            date: new Date().toISOString(),
            author: this.extractAuthor()
        };

        return Object.entries(metadata)
            .filter(([_, value]) => value) // 过滤掉空值
            .map(([key, value]) => `${key}: ${value}\n`) // 添加换行
            .join('\n'); // 在每个元数据项之间添加空行
    }

    /**
     * 提取作者信息
     * @returns {string} 作者信息
     */
    extractAuthor() {
        const authorSelectors = [
            'meta[name="author"]',
            'meta[property="article:author"]',
            '.author',
            '[rel="author"]',
            '[class*="author"]',
            '[id*="author"]'
        ];

        for (const selector of authorSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                const author = element.content || element.textContent;
                if (author && author.trim()) {
                    return author.trim();
                }
            }
        }

        return '';
    }

    /**
     * 提取标签信息
     * @returns {string} 标签信息
     */
    extractTags() {
        const tagSelectors = [
            'meta[name="keywords"]',
            'meta[property="article:tag"]',
            '.tags a',
            '[rel="tag"]',
            '[class*="tag-"]',
            '[class*="category-"]'
        ];

        const tags = new Set();

        for (const selector of tagSelectors) {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                const tag = element.content || element.textContent;
                if (tag && tag.trim()) {
                    tags.add(tag.trim());
                }
            });
        }

        return Array.from(tags).join(', ');
    }

    /**
     * 提取摘要
     * @returns {string} 文章摘要
     */
    extractExcerpt() {
        const excerptSelectors = [
            'meta[name="description"]',
            'meta[property="og:description"]',
            '.excerpt',
            '.summary',
            '[class*="excerpt"]',
            '[class*="summary"]'
        ];

        for (const selector of excerptSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                const excerpt = element.content || element.textContent;
                if (excerpt && excerpt.trim()) {
                    return excerpt.trim();
                }
            }
        }

        return '';
    }

    /**
     * 处理页面内容
     * @returns {Object} 处理结果
     */
    process() {
        try {
            const { title, content } = this.extractContent();
            const metadata = this.generateMetadata();
            const markdown = this.convertToMarkdown(content);

            return {
                success: true,
                title: title,
                pageTitle: document.title,
                markdown: `---\n${metadata}\n---\n\n${markdown}`
            };
        } catch (error) {
            console.error('处理页面内容时出错:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'ping') {
        // 响应ping消息
        sendResponse({ success: true });
        return true;
    }
    
    if (request.action === 'getPageContent') {
        const processor = new ContentProcessor();
        const result = processor.process();
        sendResponse(result);
    }
    return true; // 保持消息通道开放
}); 